package com.yk.neon.lib.util.base.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @description:
 * @author: zhurui
 * @date: 2019-01-15
 * @time: 15:33
 * Copyright (C) 2018 CASDP All rights reserved
 */
@Slf4j
public class DozerUtil {

	private static Mapper dozerMapper;

	static {
		dozerMapper = new DozerBeanMapper();
		try {
			((DozerBeanMapper) dozerMapper)
					.addMapping(new ClassPathResource("spring/bean-mappings.xml").getInputStream());
		} catch (IOException e) {
			log.error("", e);
		}
	}

	/**
	 * model转换
	 *
	 * @param source
	 * @param clazz
	 * @param <T>
	 * @param <S>
	 * @return
	 */
	public static <T, S> T convert(S source, Class<T> clazz) {
		if (Objects.isNull(source)) {
			return null;
		}
		return dozerMapper.map(source, clazz);
	}

	/**
	 * 集合转换
	 *
	 * @param source
	 * @param clazz
	 * @param <T>
	 * @param <S>
	 * @return
	 */
	public static <T, S> List<T> convert(List<S> source, Class<T> clazz) {
		if (Objects.isNull(source)) {
			return Lists.newArrayList();
		}
		List<T> list = Lists.newArrayList();
		source.forEach(s -> list.add(dozerMapper.map(s, clazz)));
		return list;
	}

	/**
	 *
	 *
	 * @param source
	 * @param clazz
	 * @param <T>
	 * @param <S>
	 * @return
	 */
	public static <T, S> Set<T> convert(Set<S> source, Class<T> clazz) {
		if (Objects.isNull(source)) {
			return Sets.newHashSet();
		}
		Set<T> set = Sets.newHashSet();
		source.forEach(s -> dozerMapper.map(s, clazz));
		return set;
	}

}
